﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using SPWP.OpinionPoll;
using System.Collections.Generic;
using System.Linq;

namespace SPWP.OpinionPoll.OpinionPollVoting
{
    public partial class OpinionPollVotingUserControl : UserControl
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (LoadQuestionResponse())
                {
                    postresponse.Visible = false;

                    LoadControlText();
                }
                else
                {
                    lblQuestion.Text = "No active poll at the moment";

                    lnkSeePreviousPoll.Text = "See previous polls";
                    lblSeePreviousPoll.Text = "See Previous Polls";
                    previousPoll.Attributes.Add("class", "invisibleDiv");
                    cnt.Attributes.Remove("class");
                }
            }
        }

        protected void grdPreviousPoll_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            res.Attributes.Remove("class");
            res.Attributes.Add("class", "invisibleDiv");

            grdPreviousPoll.PageIndex = e.NewPageIndex;
            List<PollMaster> pollList = new List<PollMaster>();

            PollVoteListAnswer objQuery = new PollVoteListAnswer("Polls", "Poll Answers");
            pollList = objQuery.ViewAllPoll();

            grdPreviousPoll.DataSource = pollList;
            grdPreviousPoll.DataBind();
        }

        protected void lnkShowResult_Click(object sender, EventArgs e)
        {
            int pollID = Convert.ToInt32(ViewState["pollID"].ToString());

            GenerateBarChart(pollID, phStat);

            phResponse.Visible = false;
            cbAnswer.Visible = false;
            rbAnswer.Visible = false;
            lnkBack.Visible = true;
            lnkShowResult.Visible = false;
            lnkVote.Visible = false;
            //postresponse.Visible = false;
            lblQuestion.Visible = true;
            cnt.Attributes.Remove("class");
            cnt.Attributes.Add("class", "visibleDiv count");

            if (lblThankYou.Visible)
                lblThankYou.Visible = false;

            //vote.Attributes.Add("class", "viewdiv");
        }

        private void GenerateBarChart(int pollID, PlaceHolder ph)
        {
            PollVoteListAnswer objQuery = new PollVoteListAnswer("Polls", "Poll Answers");

            List<ResultVote> result = objQuery.CalcResult(pollID);

            int sum = 0;
            int max = 0;

            foreach (ResultVote item in result)
            {
                sum += item.TotalCount;

                if (item.TotalCount > max)
                    max = item.TotalCount;
            }

            if (ph.ID.Equals("phStat"))
            {
                lblResultCount.Text = "Total vote(s):" + " " + String.Format("{0:n0}", sum);
                lblResultCount.Visible = true;
            }
            else
            {
                lblResultCountPrev.Text = "Total vote(s):" + " " + String.Format("{0:n0}", sum);
                lblResultCountPrev.Visible = true;
            }

            Table tab = new Table();

            foreach (ResultVote item in result)
            {
                TableRow row = new TableRow();
                TableCell cellone = new TableCell();
                TableCell celltwo = new TableCell();

                Label head = new Label();
                decimal percentage = decimal.MinValue;

                if (sum != 0)
                    percentage = ((decimal)item.TotalCount / sum) * 100;
                else
                    percentage = 0;

                head.Text = String.Format("{0} %", ((int)percentage).ToString());
                head.CssClass = "head";

                Label bar = new Label();
                bar.Width = Unit.Percentage((int)percentage);
                bar.Text = "&nbsp;";

                if (item.TotalCount.Equals(max))
                    bar.CssClass = "bar barmax";
                else
                    bar.CssClass = "bar";

                cellone.Controls.Add(head);
                celltwo.Controls.Add(bar);

                cellone.Width = Unit.Pixel(45);
                celltwo.Width = Unit.Pixel(50);

                TableCell cellthree = new TableCell();
                cellthree.Text = item.Item + "<br />" + item.TotalCount.ToString() + " " + "vote";

                row.Cells.Add(cellone);
                row.Cells.Add(celltwo);
                row.Cells.Add(cellthree);

                tab.Rows.Add(row);
            }

            ph.Controls.Add(tab);
        }

        protected void lnkBack_Click(object sender, EventArgs e)
        {
            LoadQuestionResponse();

            lnkSeePreviousPoll.Visible = true;
            grdPreviousPoll.Visible = false;
            lblSeePreviousPoll.Visible = false;
            lblQuestionResult.Visible = false;
            lblResultCount.Visible = false;
            lblResultCountPrev.Visible = false;
            lblThankYou.Visible = false;
            res.Attributes.Remove("class");
            res.Attributes.Add("class", "invisibleDiv");

            cnt.Attributes.Add("class", "invisibleDiv");
            vote.Attributes.Remove("class");
            vote.Attributes.Add("class", "viewdiv");
        }

        protected void rfvAnswerCb_OnServerValidate(object sender, ServerValidateEventArgs e)
        {
            foreach (ListItem item in cbAnswer.Items)
            {
                if (item.Selected)
                {
                    e.IsValid = true;
                    return;
                }
            }

            e.IsValid = false;
        }

        protected void ShowChart(object sender, EventArgs e)
        {
            LinkButton lnk = sender as LinkButton;
            int poll = Convert.ToInt32(lnk.CommandArgument);

            PollVoteListAnswer objQuery = new PollVoteListAnswer("Polls", "Poll Answers");
            PollMaster item = objQuery.ViewPollByID(poll);

            lblQuestionResult.Text = item.PollTitle;
            lblQuestionResult.Visible = true;
            res.Attributes.Add("class", "viewdiv visibleDiv");
            //vote.Attributes.Remove("class");

            GenerateBarChart(poll, phPrevPoll);
        }

        protected void lnkVote_Click(object sender, EventArgs e)
        {
            Page.Validate("submitVote");

            if (Page.IsValid)
            {
                List<PollVote> resultList = new List<PollVote>();

                if (ViewState["multichoice"].ToString() == "Yes")
                {
                    CheckBoxList ctrl = cbAnswer;

                    foreach (ListItem item in ctrl.Items)
                    {
                        if (item.Selected)
                        {
                            PollVote voteNew = new PollVote();
                            voteNew.AnswerPicked = item.Text;
                            voteNew.IPAddress = GetIpAddress();

                            resultList.Add(voteNew);
                        }
                    }

                    rfvAnswerCb.Enabled = false;
                }
                else
                {
                    RadioButtonList ctrl = rbAnswer;

                    if ((null != ctrl) && (null != ctrl.SelectedItem))
                    {
                        PollVote voteNew = new PollVote();
                        voteNew.AnswerPicked = ctrl.SelectedItem.Text;
                        voteNew.IPAddress = GetIpAddress();

                        resultList.Add(voteNew);

                        rfvAnswerRb.Enabled = false;
                    }
                    else
                    {
                        return;
                    }

                }

                if (null != ViewState["pollID"])
                {
                    PollVoteListAnswer query = new PollVoteListAnswer("Poll Votes-" + ViewState["pollID"].ToString());

                    if (query.AddPollAnswer(resultList))
                    {
                        postresponse.Visible = true;
                        lblQuestion.Visible = false;
                        rbAnswer.Visible = false;
                        cbAnswer.Visible = false;
                        phResponse.Visible = false;
                    }
                }

                lnkVote.Visible = false;
                lnkShowResult_Click(this, EventArgs.Empty);
                //vote.Attributes.Remove("class");
                lblThankYou.Visible = true;

            }
        }

        private void LoadControlText()
        {
            lblHeader.Text = "Opinion Poll";
            lblThankYou.Text = "Thank you for voting";
            lnkVote.Text = "Submit my vote";
            lnkBack.Text = "Back to poll";
            lnkShowResult.Text = "View Result";
            lnkSeePreviousPoll.Text = "See previous poll";
            lblSeePreviousPoll.Text = "See Previous Poll";

            cnt.Attributes.Add("class", "invisibleDiv");
            previousPoll.Attributes.Add("class", "invisibleDiv");
        }

        private string GetIpAddress()
        {
            string ipAddress = String.Empty;
            try
            {
                string ipList = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                if (!string.IsNullOrEmpty(ipList))
                {
                    ipAddress = ipList.Split(',')[0];
                }
                else
                {
                    ipAddress = Request.ServerVariables["REMOTE_ADDR"];
                }

            }
            catch (Exception ex)
            {
                return String.Empty;
            }

            return ipAddress;
        }

        private bool LoadQuestionResponse()
        {
            PollMasterAnswer objPoll = new PollMasterAnswer();
            PollVoteListAnswer objQuery = new PollVoteListAnswer("Polls", "Poll Answers");

            objPoll = objQuery.GetActivePoll();

            if (!String.IsNullOrEmpty(objPoll.PollTitle))
            {
                var pollList = from poll in objPoll.PollAnswerList
                               orderby poll.SortOrder
                               select poll;

                lblQuestion.Text = objPoll.PollTitle;

                if (null != objPoll.PollAnswerList)
                {
                    // check whether whether multiple choice is allowed
                    if (objPoll.MultiChoice.Equals("Yes"))
                    {
                        cbAnswer.Items.Clear();
                        foreach (var poll in pollList)
                        {
                            ListItem item = new ListItem(poll.Answer);
                            cbAnswer.Items.Add(item);
                        }

                        rfvAnswerCb.Enabled = true;
                        rfvAnswerCb.ErrorMessage = "Vote is required";

                        cbAnswer.Visible = true;

                    }
                    else
                    {
                        rbAnswer.Items.Clear();
                        foreach (var poll in pollList)
                        {
                            ListItem item = new ListItem(poll.Answer);
                            rbAnswer.Items.Add(item);
                        }

                        rfvAnswerRb.Enabled = true;
                        rfvAnswerRb.ErrorMessage = "Vote is required";

                        rbAnswer.Visible = true;
                    }

                    ViewState["multichoice"] = objPoll.MultiChoice;
                    ViewState["pollID"] = objPoll.PollID.ToString();

                    lnkVote.Visible = true;
                    lnkShowResult.Visible = true;
                    lblQuestion.Visible = true;
                    lnkBack.Visible = false;

                    //vote.Attributes.Add("class", "viewdiv");

                }
                return true;
            }
            else
            {
                return false; // indicate no active poll
            }
        }

        protected void lnkSeePreviousPoll_Click(object sender, EventArgs e)
        {
            List<PollMaster> pollList = new List<PollMaster>();
            PollVoteListAnswer objQuery = new PollVoteListAnswer("Polls", "Poll Answers");

            pollList = objQuery.ViewAllPoll();

            grdPreviousPoll.Columns[0].HeaderText = "No";
            grdPreviousPoll.Columns[1].HeaderText = "Opinion Poll";
            grdPreviousPoll.Columns[2].HeaderText = "Expires On";
            grdPreviousPoll.Columns[3].HeaderText = "View Result";

            grdPreviousPoll.DataSource = pollList;
            grdPreviousPoll.DataBind();
            grdPreviousPoll.Visible = true;

            lnkBack.Visible = true;
            lblSeePreviousPoll.Visible = true;

            lnkSeePreviousPoll.Visible = false;
            lblQuestion.Visible = false;
            phResponse.Visible = false;
            cbAnswer.Visible = false;
            rbAnswer.Visible = false;
            lnkShowResult.Visible = false;
            lnkVote.Visible = false;
            postresponse.Visible = false;
            lblResultCount.Visible = false;

            //vote.Attributes.Remove("class");
            vote.Attributes.Add("class", "invisibleDiv");
            previousPoll.Attributes.Remove("class");
            previousPoll.Attributes.Add("class", "visibleDiv");
        }

        protected void grdPreviousPoll_DataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton lnkShow = e.Row.FindControl("lnkShowChart") as LinkButton;
                if (lnkShow != null)
                {
                    lnkShow.Text = "View Result";
                }
            }
        }

    }
}
